﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using MySql.Data.MySqlClient;

namespace Gollie.Ajax
{
	public class NewVendorUser : AjaxResult
	{
		public NewVendorUser() : base(null) { }

		public NewVendorUser(AjaxArg arg)
			: base(arg)
		{
		}

		protected override void Init(AjaxArg ajaxArg)
		{
			RegisterVendorUserArg arg = (RegisterVendorUserArg)ajaxArg;

			logger.Info("Admin userId {0} creating new user...", arg.tokenUser);

			try
			{
				UserInfo ui = Database.Queries.GetUser(Convert.ToInt32(arg.tokenUser), true);
				if (ui == null)
					throw new Exception("Gebruiker niet gevonden.");

				string initials = UserInfo.ValidateInitials(arg.initials.Trim());
				string infix = arg.infix.Trim();
				string sex = arg.sex;
				string lastname = arg.lastname.Trim();
				string username = arg.username.Trim();
				string email = String.IsNullOrEmpty(arg.email) ? "dummy@gollie.nl" : arg.email.Trim();
				string mobile = string.IsNullOrEmpty(arg.mobile) ? "+31600000000" : arg.mobile.Trim().Replace("-", "").Replace(" ", "");
				string ww = arg.ww.Trim();
				int role = Convert.ToInt32(arg.role);

				UserInfo.ValidateWW(ww);
				UserInfo.ValidateEmail(email);
				UserInfo.ValidateUserName(username);
				mobile = UserInfo.ValidateTelePhone(mobile, false);

				/* Validation success! */
				string wwHash = Hash.GetHash(ww);

				Database.Queries.RegisterVendorUser(username, role, wwHash, email, initials, infix, lastname, sex=="1", "dummy", new DateTime(1900, 1, 1), mobile, (int)ui.VendorId);
			}
			catch (MySqlException mySqlEx)
			{
				this.ErrorCode = mySqlEx.Number;
				this.ErrorMessage = MySqlErrorCodes.GetInstance().GetMessage(mySqlEx);
				logger.Info("RegisterVendorUser failed: {0}", this.ErrorMessage);
			}
			catch (Exception e)
			{
				if (this.ErrorCode == 0)
					this.ErrorCode = 99;

				this.ErrorMessage = e.Message;
				logger.Info("RegisterVendorUser failed: {0}", this.ErrorMessage);
			}
		}
	}
}